package com.example.validate.exception;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;

@Configuration
public class GlobalExceptionHandler implements HandlerExceptionResolver {
    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        ModelAndView modelAndView = new ModelAndView();

        if (ex instanceof ConstraintViolationException) {
            ConstraintViolationException e = (ConstraintViolationException) ex;

            modelAndView.setViewName("/search");

            modelAndView.addObject("keyWords", e.getMessage());
//            如果只截取中文提示信息，截取:后面的message即可
            modelAndView.addObject("keyWords", e.getMessage().split(":")[1]);

        }

        return modelAndView;
    }
}
